from django.shortcuts import render
from django.views.generic import DetailView, UpdateView
from django.contrib.auth.models import User

import user_info
from utils.response_utils import method_disallowed_response
from .models import Profile
from .forms import ProfileForm
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from typing import Optional

# Utils functions

def contains_none(*objects) -> bool:
    """
    检查参数列表中是否包含None
    :param objects: 变长参数列表
    :return: 是否包含None
    """
    for o in objects:
        if o is None:
            return True
    return False

def contains_false_val(*objects) -> bool:
    """
    检查参数列表中是否包含布尔值为False的值
    :param objects: 变长参数列表
    :return: 是否包含布尔值为False的值
    """
    for o in objects:
        if not o:
            return True
    return False

def valid_email(email: str) -> bool:
    """
    使用正则表达式验证邮箱格式是否合法
    :param email: 邮箱字符串
    :return: 邮箱格式是否合法
    """
    import re
    if re.match(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$', email):
        return True
    else:
        return False

def build_response(other_info: Optional[dict] = None, *, errno: int = 1, msg: str = "操作成功", status: int = 200):
    """
    构建JSON响应
    :param other_info: 响应体的其他信息
    :param errno: 错误码
    :param msg: 提示信息
    :param status: HTTP状态码
    :return: JSON响应
    """
    if other_info is None:
        other_info = {}
    response_dict = {
        "errno": errno,
        "msg": msg,
    }
    response_dict.update(other_info)
    return JsonResponse(response_dict, status=status)

@csrf_exempt
def get_info(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    nickname1 = request.GET.get('username')
    x=Profile.objects.filter(nickname=nickname1)
    print(x.count())
    if x.count() == 0:
        return build_response(errno=58983, msg='企业不存在')

    #profile = Profile.objects.filter(nickname=nickname1)[0]
    #profile = x[0]
    firm_info = x[0].parse_dict()
    firm_info['success'] = True
    return build_response(other_info=firm_info, errno=1)

@method_decorator(login_required, name='dispatch')
@method_decorator(csrf_exempt, name='dispatch')
class ProfileUpdateView(UpdateView):
    """
    ProfileUpdateView 视图用于更新用户的个人资料
    """
    model = Profile
    form_class = ProfileForm
    template_name = 'user_info/profile_update.html'
    context_object_name = 'profile'

    def get_object(self):
        """
        根据URL中的用户名参数获取对应的用户对象，并返回该用户的Profile对象
        """
        user = User.objects.get(username=self.kwargs.get('username'))
        return user.profile

    def form_valid(self, form):
        """
        当表单验证通过时，保存表单数据，并返回包含更新后数据的JSON响应
        """
        self.object = form.save()
        response_data = {
            'success': True,
            'message': 'Profile updated successfully',
            'data': {
                'nickname': self.object.nickname,
                'full_name': self.object.full_name,
                'education': self.object.education,
                'interested_position': self.object.interested_position,
                'blog_or_repo_link': self.object.blog_or_repo_link,
                'work_experience': self.object.work_experience,
                'job_title': self.object.job_title,
                'resume': self.object.resume.url if self.object.resume else None,
                'can_add_extra_info': self.object.can_add_extra_info(),
            }
        }
        return JsonResponse(response_data)

    def form_invalid(self, form):
        """
        当表单验证失败时，返回包含错误信息的JSON响应
        """
        response_data = {
            'success': False,
            'errors': form.errors
        }
        return JsonResponse(response_data, status=400)

    def post(self, request, *args, **kwargs):
        """
        在进行表单处理之前，验证请求数据的有效性。如果数据无效，返回相应的JSON错误响应
        """
        data = request.POST
        nickname = data.get('nickname')
        full_name = data.get('full_name')
        education = data.get('education')
        interested_position = data.get('interested_position')
        blog_or_repo_link = data.get('blog_or_repo_link')
        work_experience = data.get('work_experience')
        job_title = data.get('job_title')

        # 检查必填字段是否为空
        if contains_none(nickname, full_name, education, interested_position):
            return build_response(errno=2001, msg="Nickname, full name, education, and interested position are required", status=400)

        # 检查必填字段是否包含布尔值为False的值
        if contains_false_val(nickname, full_name, education, interested_position):
            return build_response(errno=2002, msg="Nickname, full name, education, and interested position must have valid values", status=400)

        # 检查昵称的长度和格式
        if not (2 <= len(nickname) <= 31) or valid_email(nickname):
            return build_response(errno=2003, msg="Nickname is not valid", status=400)

        # 检查教育和兴趣岗位字段的长度
        if not (2 <= len(education) <= 100):
            return build_response(errno=2004, msg="Education length is not valid", status=400)
        if not (2 <= len(interested_position) <= 100):
            return build_response(errno=2005, msg="Interested position length is not valid", status=400)

        # 博客或仓库链接验证（如果填写）
        if blog_or_repo_link:
            url_validator = URLValidator()
            try:
                url_validator(blog_or_repo_link)
            except ValidationError:
                return build_response(errno=2006, msg="Blog or repository link is not valid", status=400)

        return super().post(request, *args, **kwargs)

    def get_success_url(self):
        """
        此方法在返回JSON数据时不会实际使用，但保留以防需要
        """
        return reverse_lazy('profile_detail', kwargs={'username': self.object.user.nickname})
